package com.bl.nio.server.handler;

import com.bl.nio.common.entity.SocketClient;
import com.bl.nio.common.handler.IEventHandler;
import com.bl.nio.common.pack.EventPack;
import com.bl.nio.common.pack.HeartbeatPack;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 10:49
 * @describe 类描述:
 */
public class ClientHandler implements Runnable{
    private SocketClient client;
    private IEventHandler eventHandler;


    public ClientHandler(SocketClient client,IEventHandler eventHandler) {
        this.client = client;
        this.eventHandler = eventHandler;

        eventHandler.onConnect(client);
    }

    @Override
    public void run() {
        int times = 0;
        while (client.getSocket().isConnected() && !client.getSocket().isClosed()){
            try {
                InputStream in = client.getSocket().getInputStream();
                int available = in.available();
                if (available > 0){
                    Object object = client.read();
                    if (object instanceof HeartbeatPack){  //心跳包
                        times = 0;
                        HeartbeatPack heartbeatPack = (HeartbeatPack)object;
                        if (heartbeatPack.getStatus() == 0){
                            client.close();
                            break;
                        }
                        eventHandler.onHeartbeatPack(client,heartbeatPack);
                    }else if (object instanceof EventPack){
                        eventHandler.onEventPack(client,(EventPack)object);
                    }
                    eventHandler.onMessage(client,object);
                }
                Thread.sleep(100);

                times += 100;
                if (times >= client.getTimeout() && client.getTimeout() != 0){
                    client.getSocket().close();
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        eventHandler.onDisConnect(client);
    }
}
